<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    @include('common-css')
    <style>

        .input_box {
            width: 100%;
            height: 40px;
            margin-top: 15px;
            margin-bottom: 15px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
        }

        .input_label {
            width: 120px;
            box-sizing: border-box;
        }

        .project-table {
            margin-top: 15px;
        }

        .status-tag {
            color: #1890ff;
            border: 1px solid #91d5ff;
            border-radius: 3px;
            background: #e6f7ff;
            font-size: 12px;
            padding: 2px 3px;
        }

        .ant-table-tbody > tr > td, .ant-table-thead > tr > th {
            vertical-align: middle;
            line-height: 25px;
        }

        .search_box {
            width: 1000px;
        }

        .search_box input {
            width: 300px;
        }

        .search_box button {
            margin-left: 20px;
        }

        .search_box .ant-select {
            margin-left: 20px;
        }
    </style>
</head>
<body>


<div id="app"></div>


<script id="appTemplate" type="x-template">
    <a-locale-provider :locale="antdLocale">
        <div class="container">

            @include('admin.header-tpl')

            <main>
                <div class="common_container">

                    @include('admin.aside-tpl')

                    <div class="common_content admin_common_content">

                        <div style="margin-top: 20px; margin-bottom: 20px">
                            <span style="font-weight: bold">分数线：</span>
                            <template v-for="award in awards">
                                <span style="margin-left: 20px;">@{{ award.name }}</span>
                                <a-input-number :disabled="notAtPhasePlanAward" size="small"
                                                :min="0" :max="100" :precision="2"
                                                v-model="award.min_score"/>
                            </template>
                            <a-button :disabled="notAtPhasePlanAward" style="margin-left: 40px;" type="primary"
                                      @click="handleAutoSetAwardLevel">
                                自动设置授奖等级
                            </a-button>
                        </div>
                        <p v-if="hasPhasePlanAwardBegun && pageData.length > 0" style="margin-top: 20px; margin-bottom: 20px">
                            <template v-for="item,i in projectAwardStats.perAward">
                                <span>@{{ item.name }} @{{ item.count }} 个，占比 @{{ item.percent }}%</span>
                                <span>@{{ i < projectAwardStats.perAward.length - 1 ? '；' : '。'}}</span>
                            </template>
                            <span>累计 @{{ projectAwardStats.totalCount }} 个，累计占比 @{{ projectAwardStats.totalPercent }}%。</span>
                        </p>
                        <div style="margin-top: 20px; margin-bottom: 20px">
                            <template v-if="atPhasePlanAward">
                                <a-popconfirm title="提交后不能撤销，确认提交？" okText="是" cancelText="否"
                                              @confirm="submitPlanAwardResult">
                                    <a-button type="primary">提交拟授奖等级至委员投票</a-button>
                                </a-popconfirm>
                            </template>
                            <a-button v-else :disabled="true" type="primary">提交拟授奖等级至委员投票</a-button>
                        </div>

                        <a-tabs defaultActiveKey="planned_project_awards" type="card" @change="">
                            <a-tab-pane tab="项目拟授奖等级" key="planned_project_awards">
                                <a-table class="project-table"
                                         rowKey="id"
                                         size="small"
                                         :columns="projectTableColumns"
                                         :dataSource="filteredProjects"
                                         :loading="loadingPageData"
                                         :pagination="{pageSize: 10000, hideOnSinglePage: true, position: 'both', showTotal: total => `共 ${total} 项`}">
                            <span slot="application_form" slot-scope="text, record">
                                <a :href="'/home/view-form?id=' + record.id" target="_blank">查看</a>
                            </span>
                                    <span slot="attachments" slot-scope="text, record">
                                <a :href="'/home/view-attachments?project_id=' + record.id" target="_blank">
                                    <span>查看</span>
                                </a>
                            </span>
                                    <span slot="planned_award_level" slot-scope="text, record">
                                <a-select :disabled="notAtPhasePlanAward" style="width: 140px;" size="small"
                                          v-model="record.planned_award_level"
                                          @change="handleUpdatePlannedAwardLevel(record)">
                                    <a-select-option disabled :value="''" key="未指定">未指定</a-select-option>
                                    <a-select-option v-for="award of awards" :value="award.name" :key="award.name">@{{award.name}}</a-select-option>
                                </a-select>
                            </span>
                                </a-table>
                            </a-tab-pane>

                            <a-tab-pane tab="项目分数段表" key="project_score_segments">
                                <a-table
                                        class="project-table"
                                        rowKey="num"
                                        size="small"
                                        bordered
                                        :columns="projectScoreSegmentTableColumns"
                                        :dataSource="filteredProjectScoreSegments"
                                        :loading="loadingPageData"
                                        :pagination="{pageSize: 10000, hideOnSinglePage: true, position: 'both', showTotal: total => `共 ${total} 项`}">
                                </a-table>
                            </a-tab-pane>
                        </a-tabs>
                    </div>

                </div>
            </main>

        </div>
    </a-locale-provider>
</script>

@include('common-js')
@include('admin.header-js')
@include('admin.aside-js')

<script>
    var queryParams = parseUrl(location.href).params;
    var awardsInfo = {!! json_encode(array_values(config('vars.awards')), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) !!};

    var projectTableColumns = [
        {
            width: 60,
            title: '序号',
            dataIndex: 'num'
        },
        {
            width: 150,
            title: '项目名称',
            dataIndex: 'project_name',
        },
        {
            width: 100,
            title: '申报者',
            dataIndex: 'applicant',
        },
        {
            width: 70,
            title: '申报书',
            dataIndex: 'application_form',
            scopedSlots: {
                customRender: 'application_form'
            }
        },
        {
            width: 70,
            title: '附件',
            dataIndex: 'attachments',
            scopedSlots: {
                customRender: 'attachments'
            }
        },
        {
            width: 60,
            title: '分数',
            dataIndex: 'avg_score'
        },
        {
            width: 150,
            title: '拟授奖等级',
            dataIndex: 'planned_award_level',
            // scopedSlots: {
            //     customRender: 'planned_award_level'
            // }
        }
    ];

    var projectScoreSegmentTableColumns = [
        {
            title: '一',
            children: [
                {
                    width: 60,
                    title: '分数',
                    dataIndex: 'avg_score1'
                },
                {
                    width: 60,
                    title: '累计项目数',
                    dataIndex: 'accum_projects1',
                },
                {
                    width: 60,
                    title: '累计百分比',
                    dataIndex: 'accum_percent1',
                },
            ],
        },
        {
            title: '二',
            children: [
                {
                    width: 60,
                    title: '分数',
                    dataIndex: 'avg_score2'
                },
                {
                    width: 60,
                    title: '累计项目数',
                    dataIndex: 'accum_projects2',
                },
                {
                    width: 60,
                    title: '累计百分比',
                    dataIndex: 'accum_percent2',
                },
            ],
        },
        {
            title: '三',
            children: [
                {
                    width: 60,
                    title: '分数',
                    dataIndex: 'avg_score3'
                },
                {
                    width: 60,
                    title: '累计项目数',
                    dataIndex: 'accum_projects3',
                },
                {
                    width: 60,
                    title: '累计百分比',
                    dataIndex: 'accum_percent3',
                },
            ],
        },
        {
            title: '四',
            children: [
                {
                    width: 60,
                    title: '分数',
                    dataIndex: 'avg_score4'
                },
                {
                    width: 60,
                    title: '累计项目数',
                    dataIndex: 'accum_projects4',
                },
                {
                    width: 60,
                    title: '累计百分比',
                    dataIndex: 'accum_percent4',
                },
            ],
        },
        {
            title: '五',
            children: [
                {
                    width: 60,
                    title: '分数',
                    dataIndex: 'avg_score5'
                },
                {
                    width: 60,
                    title: '累计项目数',
                    dataIndex: 'accum_projects5',
                },
                {
                    width: 60,
                    title: '累计百分比',
                    dataIndex: 'accum_percent5',
                },
            ],
        },
    ];
</script>

<script>
    var app = new Vue({
        el: '#app',
        template: '#appTemplate',
        data: {
            profCategoryFilter: '',
            searchKeyword: '',

            projectTableColumns,
            pageData: [],
            loadingPageData: false,
            projectScoreSegmentTableColumns,
            projectScoreSegments: [],
            PROJECT_SCORE_SEGMENT_GROUPS: 5,  // 项目分数段表的组数

            hasPhasePlanAwardBegun: false,
            atPhasePlanAward: false,
            awards: [],

            queryParams,
            awardsInfo,
            profCategories,

            asideSelectedKeys: queryParams.aside_key ? [queryParams.aside_key] : [],
            antdLocale: antd.locales.zh_CN,
            ...AdminHeader.data,
            ...AdminAside.data,
        },
        beforeMount() {
            this.loadAsideDefaultOpenKeys()
        },
        computed: {
            notAtPhasePlanAward() {
                return !this.atPhasePlanAward
            },
            projectAwardStats() {
                let result = {totalCount: 0, totalPercent: null, perAward: []}
                let perAward = result.perAward;
                let name2index = {};
                let i = 0;
                this.awards.forEach(award => {
                    name2index[award.name] = i++;
                    perAward.push({name: award.name, count: 0, percent: null})
                });
                let projectCount = this.pageData.length
                if (projectCount === 0) {
                    return result
                }

                for (let project of this.pageData) {
                    let awardName = project.planned_award_level;
                    if (awardName) {
                        perAward[name2index[awardName]].count++
                        result.totalCount++
                    }
                }
                for (let item of perAward) {
                    item.percent = Math.round(item.count / projectCount * 10000) / 100
                }
                result.totalPercent = Math.round(result.totalCount / projectCount * 10000) / 100
                return result
            },
            filteredProjects() {
                var projects = this.searchFilteredProjects;
                if (this.profCategoryFilter) {
                    projects = projects.filter(project => {
                        return project.prof_category == this.profCategoryFilter
                    })
                }
                var num = 1;
                projects.forEach(project => {
                    project.num = num++
                });
                return projects
            },
            searchFilteredProjects() {
                var projects;
                if (this.searchKeyword) {
                    var q = this.searchKeyword.trim();
                    projects = this.pageData.filter(project => {
                        var text = project.project_name + project.applicant_name + project.applicant_org_name + project.applicant_tel + project.applicant_email;
                        return text.toLowerCase().indexOf(q) != -1
                    })
                } else {
                    projects = this.pageData
                }
                return projects
            },
            filteredProjectScoreSegments() {
                let oldSegmentCount = this.projectScoreSegments.length
                if (oldSegmentCount === 0) {
                    return [];
                }
                let segments = Array.from(this.projectScoreSegments)
                let segmentGroupCount = this.PROJECT_SCORE_SEGMENT_GROUPS
                let segmentGroupSize = Math.ceil(oldSegmentCount / segmentGroupCount)
                let newSegmentCount = segmentGroupSize * segmentGroupCount
                let paddingSegmentCount = newSegmentCount - oldSegmentCount;
                for (let i = 0; i < paddingSegmentCount; i++) {
                    segments.push({avg_score: null, segment_projects: null, accum_projects: null, accum_percent: null})
                }
                let segmentGroups = this.arrayChunk(segments, segmentGroupSize)
                let result = [];
                let keys = ['avg_score', 'segment_projects', 'accum_projects', 'accum_percent']
                for (let i = 0; i < segmentGroupSize; i++) {
                    let row = {num: i + 1}
                    for (let j = 0; j < segmentGroupCount; j++) {
                        for (let key of keys) {
                            let targetKey = key + (j + 1)
                            row[targetKey] = segmentGroups[j][i][key]
                        }
                    }
                    result.push(row)
                }
                return result
            },
        },
        mounted() {
            this.reloadPageData();
        },
        methods: {
            arrayChunk(array, size) {
                return Array.from({length: Math.ceil(array.length / size)}, (v, i) =>
                    array.slice(i * size, i * size + size)
                );
            },
            handleAutoSetAwardLevel() {
                let awards = this.awards
                for (let award of awards) {
                    if (typeof award.min_score !== 'number') {
                        error(`请设置 ${award.name} 的比例`);
                        return
                    }
                }
                for (let i = 1; i < awards.length; i++) {
                    let curAward = awards[i]
                    let previousAward = awards[i - 1]
                    if (curAward.min_score >= previousAward.min_score) {
                        error(`${curAward.name} 的分数线应小于 ${previousAward.name}`)
                        return
                    }
                }
                axios.post('/api/admin/auto-set-award-level', {
                    large_group_id: queryParams.large_group_id,
                    awards,
                }).then(response => {
                    let data = response.data;
                    if (data.ok) {
                        success('自动设置授奖等级成功');
                        this.reloadPageData()
                    } else {
                        error('自动设置授奖等级失败: ' + data.msg)
                    }
                })
            },
            handleUpdatePlannedAwardLevel(project) {
                axios.post('/api/admin/update-planned-award-level', {
                    project_id: project.id,
                    planned_award_level: project.planned_award_level,
                }).then(response => {
                    let data = response.data;
                    if (data.ok) {
                        success('修改授奖等级成功')
                    } else {
                        error('修改授奖等级失败: ' + data.msg)
                    }
                })
            },
            submitPlanAwardResult() {
                axios.post('/api/admin/submit-plan-award-result', {
                    large_group_id: queryParams.large_group_id,
                }).then(response => {
                    let data = response.data;
                    if (data.ok) {
                        success('提交成功');
                        this.reloadPageData()
                    } else {
                        error('提交失败: ' + data.msg)
                    }
                })
            },
            reloadPageData() {
                this.loadingPageData = true;
                axios.get('/api/admin/get-plan-award-page-data', {
                    params: {
                        large_group_id: queryParams.large_group_id,
                    }
                }).then(response => {
                    if (response.data.ok) {
                        this.hasPhasePlanAwardBegun = response.data.hasPhasePlanAwardBegun;
                        this.atPhasePlanAward = response.data.atPhasePlanAward;
                        this.awards = response.data.largeGroup.attrs.award.awards;
                        this.pageData = response.data.projects
                        this.projectScoreSegments = response.data.project_score_segments
                    } else {
                        error('加载页面数据失败: ' + response.data.msg)
                    }
                    this.loadingPageData = false
                })
            },
            ...AdminHeader.methods,
            ...AdminAside.methods,
        }
    })
</script>

</body>
</html>